package com.guoxue.action.common;
import java.io.UnsupportedEncodingException;

import org.springframework.stereotype.Component;

import com.aliyun.oss.common.auth.HmacSHA1Signature;
@Component
public class ForSTSSignature {
//	Signature = base64(hmac-sha1(AccessKeySecret,
//            VERB + "\n” 
//            + Content-MD5 + "\n" 
//            + Content-Type + "\n" 
//            + Date + "\n" 
//            + CanonicalizedOSSHeaders
//            + CanonicalizedResource))
	/**
	 * 处理GET请求时的Signature生成
	 * @param bucket 授权访问oss的指定bucket
	 * @param accessKeySecret 临时ak密钥
	 * @param key 授权访问的文件名
	 * @param xOSSSecurityToken 临时ak的token
	 * @param expire 签名过期时间（<=临时AK的过期时间）
	 * @return
	 *@author kanghongbo
	 *@date 2016年11月15日下午5:27:06
	 */
	public String ForGETSignature(String bucket,String accessKeySecret,String key,String xOSSSecurityToken,Long expire){
		String signature="";
		String canonicalizedOSSHeaders="";
		StringBuffer strB=new StringBuffer();
		if(key==null||"".equals(key)){
			strB.append("/"+bucket+"/");
		}else{
			strB.append("/"+bucket+"/"+key);
		}
		if(xOSSSecurityToken!=null||!"".equals(xOSSSecurityToken)){
			strB.append("?security-token="+xOSSSecurityToken);
			//canonicalizedOSSHeaders="x-oss-security-token:"+xOSSSecurityToken+"\n";
		}
		//CanonicalizedResource
		//CanonicalizedOSSHeaders
		String canonicalizedResource=strB.toString();
		String forString="GET\n\n\n"+expire+"\n"+canonicalizedOSSHeaders+canonicalizedResource;
		HmacSHA1Signature hmacSHA1Signature=new HmacSHA1Signature();	
		signature=hmacSHA1Signature.computeSignature(accessKeySecret, forString);
		//signature=URLEncoder.encode(signature);
		return signature;
	}
	/**
	 * 处理POST请求时的Signature生成
	 * @param accessKeySecret 临时ak密钥
	 * @param policy 临时ak的授权控制的base64编码后的字符串
	 * @return
	 *@author kanghongbo
	 * @throws UnsupportedEncodingException 
	 *@date 2016年11月15日下午5:27:06
	 */
	public String ForPOSTSignature(String accessKey,String policy) throws UnsupportedEncodingException{
		String signature="";
		HmacSHA1Signature hmacSHA1Signature=new HmacSHA1Signature();	
		signature=hmacSHA1Signature.computeSignature(accessKey, policy);
		return signature;
	}
}
